package com.lagou.rpc.consumer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 每个Server处理请求耗时的缓存类
 */
public class ServerRequestCostTimeCache {
    private ServerRequestCostTimeCache() {}

    private static final Map<String, Long> serverCostTimeMap = new ConcurrentHashMap<>();
    private static final long DEFAULT_COST_TIME_WHEN_FIRST_REQUEST = 0L;

    /**
     * 获取指定server的最后一次请求处理耗时key为"ip:port"的形式，找不到时默认返回0
     * @param key
     * @return
     */
    public static long getLastCostTime(String key) {
        return serverCostTimeMap.getOrDefault(key, DEFAULT_COST_TIME_WHEN_FIRST_REQUEST);
    }

    public static void update(String key, long costTime) {
        serverCostTimeMap.put(key, costTime);
    }
}
